import React, { Component, createRef } from 'react'
import { Modal, Form, Input, Button, Upload, Row, Col, message } from 'antd'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'

import { getRcode, register } from '../../api/user'

export default class Register extends Component {
  constructor () {
    super()

    this.state = {
      visible: false, // 控制窗口是否显示
      registerCaptcha: process.env.REACT_APP_BASEURL + '/captcha?type=sendsms', // 注册时候的图形码地址
      action: process.env.REACT_APP_BASEURL + '/uploads', // 上传头像地址
      imageUrl: '', // 头像预览地址
      loading: false, // 头像是否正在上传
      fileList: []
    }

    this.uploadData = {
      // 上传需要的额外参数
      image: null
    }

    this.formRef = createRef()
  }

  setVisible = visible => {
    this.setState({
      visible
    })
  }

  changeRegisterCaptcha = () => {
    this.setState({
      registerCaptcha:
        process.env.REACT_APP_BASEURL +
        `/captcha?type=sendsms&t=${new Date() - 0}`
    })
  }

  beforeUpload = file => {
    const isImage =
      file.type === 'image/jpeg' ||
      file.type === 'image/png' ||
      file.type === 'image/gif'
    if (!isImage) {
      message.error('上传头像必须是 JPEG/PNG/GIF 格式的!')
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('头像上传的大小不能超过 2MB!')
    }

    this.uploadData.image = file

    return isImage && isLt2M
  }

  getBase64 = (img, callback) => {
    const reader = new FileReader()
    reader.addEventListener('load', () => callback(reader.result))
    reader.readAsDataURL(img)
  }

  handleChange = info => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true })
      return
    }

    if (info.file.status === 'done') {
      // Get this url from response in real world.
      this.getBase64(info.file.originFileObj, imageUrl =>
        this.setState({
          imageUrl,
          loading: false
        })
      )

      if (info.file.response.code === 200) {
        this.formRef.current.setFieldsValue({
          avatar: info.file.response.data.file_path
        })
      } else {
        message.error(info.file.response.message)
      }
    }
  }

  // 获取验证码
  onGetRcode = async () => {
    try {
      const values = await this.formRef.current.validateFields([
        'phone',
        'code'
      ])

      const res = await getRcode(values)

      if (res.code === 200) {
        this.formRef.current.setFieldsValue({
          rcode: res.data.captcha
        })
      } else {
        message.error(res.message)

        this.changeRegisterCaptcha()
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo)
    }
  }

  // 注册
  onOk = async () => {
    try {
      const values = await this.formRef.current.validateFields()

      const res = await register(values)
      if (res.code === 200) {
        message.success('注册成功~')

        this.onCancel()
      } else {
        message.error(res.message)

        this.changeRegisterCaptcha()
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo)
    }
  }

  // 取消
  onCancel = () => {
    this.formRef.current.resetFields()

    this.setVisible(false)
  }

  render () {
    const { visible, action, imageUrl, loading, fileList } = this.state
    return (
      <div>
        <Modal
          title='注册'
          centered
          visible={visible}
          cancelText='取消'
          okText='确定'
          onOk={this.onOk}
          onCancel={this.onCancel}
          width={600}
        >
          <Form ref={this.formRef} size='large'>
            <Form.Item
              label='头像'
              name='avatar'
              rules={[{ required: true, message: '头像不能为空!' }]}
            >
              <Upload
                name='avatar'
                listType='picture-card'
                className='avatar-uploader'
                showUploadList={false}
                action={action}
                data={this.uploadData}
                beforeUpload={this.beforeUpload}
                onChange={this.handleChange}
                fileList={fileList}
              >
                {imageUrl ? (
                  <img className='avatarImg' src={imageUrl} alt='avatar' />
                ) : (
                  <div>{loading ? <LoadingOutlined /> : <PlusOutlined />}</div>
                )}
              </Upload>
            </Form.Item>
            <Form.Item
              label='昵称'
              name='username'
              rules={[{ required: true, message: '昵称不能为空!' }]}
              validateTrigger='onBlur'
            >
              <Input />
            </Form.Item>
            <Form.Item
              label='邮箱'
              name='email'
              rules={[
                { required: true, message: '邮箱不能为空!' },
                { type: 'email', message: '邮箱不合法!' }
              ]}
              validateTrigger='onBlur'
            >
              <Input />
            </Form.Item>
            <Form.Item
              label='手机'
              name='phone'
              rules={[
                {
                  required: true,
                  validator: (_, value) => {
                    if (!value) return Promise.reject('手机号不能为空')

                    const reg = /^1[3456789][0-9]{9}$/
                    if (!reg.test(value)) return Promise.reject('手机号不合法')

                    return Promise.resolve()
                  }
                }
              ]}
              validateTrigger='onBlur'
            >
              <Input />
            </Form.Item>
            <Form.Item
              label='密码'
              name='password'
              rules={[
                { required: true, message: '密码不能为空!' },
                { max: 16, min: 6, message: '密码长度必须是6-16位之间!' }
              ]}
              validateTrigger='onBlur'
            >
              <Input type='password' />
            </Form.Item>
            <Row>
              <Col span={16}>
                <Form.Item
                  label='图形码'
                  name='code'
                  rules={[{ required: true, message: '图形码不能为空!' }]}
                  validateTrigger='onBlur'
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={7} style={{ marginLeft: '10px' }}>
                <img
                  onClick={this.changeRegisterCaptcha}
                  style={{ width: '100%', height: '40px' }}
                  src={this.state.registerCaptcha}
                  alt=''
                />
              </Col>
            </Row>
            <Row>
              <Col span={16}>
                <Form.Item
                  label='验证码'
                  name='rcode'
                  rules={[{ required: true, message: '验证码不能为空!' }]}
                  validateTrigger='onBlur'
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={7} style={{ marginLeft: '10px' }}>
                <Button onClick={this.onGetRcode}>获取用户验证码</Button>
              </Col>
            </Row>
          </Form>
        </Modal>
      </div>
    )
  }
}
